package com.iot.protocol;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class TcpClientSimulator {
    private final String serverHost;
    private final int serverPort;
    private final int clientCount;
    private final ExecutorService executorService;
    private final List<TcpClient> clients;
    private final AtomicInteger activeClients;
    private volatile boolean running;

    public TcpClientSimulator(String serverHost, int serverPort, int clientCount) {
        this.serverHost = serverHost;
        this.serverPort = serverPort;
        this.clientCount = clientCount;
        this.executorService = Executors.newFixedThreadPool(clientCount);
        this.clients = new ArrayList<>(clientCount);
        this.activeClients = new AtomicInteger(0);
        this.running = true;
    }

    public void start() {
        log.info("开始模拟 {} 个客户端连接到服务器 {}:{}", clientCount, serverHost, serverPort);
        CountDownLatch startLatch = new CountDownLatch(1);

        // 创建并启动所有客户端
        for (int i = 0; i < clientCount; i++) {
            final int clientId = i + 1;
            executorService.execute(() -> {
                try {
                    // 等待所有客户端准备就绪
                    startLatch.await();
                    
                    TcpClient client = new TcpClient(serverHost, serverPort) {
                        @Override
                        public void sendMessage(String message) {
                            super.sendMessage(String.format("[Client-%d] %s", clientId, message));
                        }
                    };
                    clients.add(client);
                    activeClients.incrementAndGet();
                    log.info("客户端-{} 已连接", clientId);

                    // 模拟客户端定期发送消息
                    while (running) {
                        String message = String.format("Hello from client-%d at %s", 
                            clientId, java.time.LocalTime.now());
                        client.sendMessage(message);
                        TimeUnit.SECONDS.sleep(5);
                    }
                } catch (Exception e) {
                    log.error("客户端-{} 发生错误: {}", clientId, e.getMessage(), e);
                } finally {
                    activeClients.decrementAndGet();
                }
            });
        }

        // 启动所有客户端
        startLatch.countDown();

        // 等待用户输入来控制模拟器
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("模拟器已启动，输入命令控制：");
            System.out.println("'status' - 查看当前状态");
            System.out.println("'broadcast <message>' - 向所有客户端广播消息");
            System.out.println("'exit' - 退出模拟器");

            while (running) {
                String command = scanner.nextLine().trim();
                if ("exit".equalsIgnoreCase(command)) {
                    break;
                } else if ("status".equalsIgnoreCase(command)) {
                    showStatus();
                } else if (command.startsWith("broadcast ")) {
                    String message = command.substring("broadcast ".length());
                    broadcastMessage(message);
                } else {
                    System.out.println("未知命令，可用命令：status, broadcast <message>, exit");
                }
            }
        }

        // 关闭所有客户端
        shutdown();
    }

    private void showStatus() {
        System.out.printf("当前状态：\n" +
                "总客户端数：%d\n" +
                "活跃客户端数：%d\n" +
                "服务器地址：%s:%d\n",
                clientCount, activeClients.get(), serverHost, serverPort);
    }

    private void broadcastMessage(String message) {
        log.info("广播消息到所有客户端: {}", message);
        for (TcpClient client : clients) {
            try {
                client.sendMessage("[Broadcast] " + message);
            } catch (Exception e) {
                log.error("广播消息失败: {}", e.getMessage(), e);
            }
        }
    }

    private void shutdown() {
        running = false;
        log.info("正在关闭模拟器...");
        
        // 关闭所有客户端
        for (TcpClient client : clients) {
            try {
                client.close();
            } catch (Exception e) {
                log.error("关闭客户端时发生错误: {}", e.getMessage(), e);
            }
        }
        
        // 关闭线程池
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
            Thread.currentThread().interrupt();
        }
        
        log.info("模拟器已关闭");
    }

    public static void main(String[] args) {
        String serverHost = "localhost";
        int serverPort = 8888;
        int clientCount = 5; // 默认模拟5个客户端

        if (args.length >= 1) {
            clientCount = Integer.parseInt(args[0]);
        }
        if (args.length >= 2) {
            serverHost = args[1];
        }
        if (args.length >= 3) {
            serverPort = Integer.parseInt(args[2]);
        }

        TcpClientSimulator simulator = new TcpClientSimulator(serverHost, serverPort, clientCount);
        simulator.start();
    }
} 